package com.niit.activity.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableTransactionManagement
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // 前后端分离必须关闭 CSRF
            .cors().and() // 支持跨域
            .authorizeHttpRequests(authz -> authz
                .antMatchers(
                    "/activity/public",
                    "/activity/*/toggle-like",
                        "/activity/*/is-liked",
                    "/comments/activity/*",
                        "/comments"

                ).permitAll() // 允许匿名访问
                    .anyRequest().permitAll() // 临时关闭所有认证，开发测试用
            );
        return http.build();
    }

    // 全局CORS配置
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOriginPatterns("*")
                        .allowedMethods("*")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }
} 